from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.db.db import get_db
from app.schemas.schemas import UserCreate, User
from app.security.security import (
    get_password_hash,
    verify_password,
    create_access_token,
)
from datetime import timedelta
from app.dependencies import get_current_active_user

from app.db import crud

router = APIRouter(tags=["auth"])


@router.post("/login")
def login(
    form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
):
    user = crud.get_user_by_username(db, form_data.username)
    if not user or not verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=30)
    token = create_access_token(
        {"user_id": user.id}, expires_delta=access_token_expires
    )
    return {"access_token": token, "token_type": "bearer"}
